<template>
  <div class="product-develop">
    <div class="product-content">
      <el-scrollbar ref="scrollbarRef" always height='810px'>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <div class="list-card" infinite-scroll-immediate="false">
            <div class="list-card-item add-card" @click="handleAdd">
              <img src="@/assets/images/develop_add.png" />
              <span class="textgray">点击添加</span>
            </div>
            <div class="list-card-item" v-for="(item, index) of listData" :key="index">
              <div class="product_normal" @click="handleAddDetail(item.id)">
                <div class="normal-one">
                  <span class="one-left">{{ item.name }}</span>
                  <span class="one-right">
                    <el-popover placement="bottom" trigger="hover" popper-class="custom-popover-aig">
                      <template #reference>
                        <img src="@/assets/images/three_diot.png" />
                      </template>
                      <template #default>
                        <div class="popover-btn">
                          <div class="popover-item" @click="handleCopy(item)">
                            <img src="@/assets/images/popover_copy.png" /><span>复制</span>
                          </div>
                          <div class="popover-item" @click="handleDel(item)">
                            <img src="@/assets/images/popover_del.png" /><span>删除</span>
                          </div>
                          <div class="popover-item" @click="handleAddDetail(item.id)">
                            <img src="@/assets/images/popover_view.png" /><span>查看</span>
                          </div>
                        </div>
                      </template>
                    </el-popover>
                  </span>
                </div>
                <div class="normal-two">
                  <span class="two-left">ProdID</span>
                  <span class="two-right">{{ item.prodId }}</span>
                </div>
                <div class="normal-two">
                  <span class="two-left">产品型号</span>
                  <span class="two-right">{{ item.model }}</span>
                </div>
                <div class="normal-two">
                  <span class="two-left">产品类型</span>
                  <span class="two-right">{{ item.type }}</span>
                </div>
                <div class="normal-two">
                  <span class="two-left">创建时间</span>
                  <span class="two-right">{{ item.createTime }}</span>
                </div>
                <div class="normal-two">
                  <span class="two-left">审核状态</span>
                  <span class="two-right">{{
                    item.status === '0' ? '待提交' :
                    item.status === '1' ? '待审核' :
                    item.status === '2' ? '审核通过' :
                    item.status === '3' ? '审核驳回' :
                    '-' }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-scrollbar>
    </div>

    <!-- 添加产品 -->
    <addProduct ref="addProductRef" @addSuccess="addSuccess"></addProduct>
  </div>
</template>

<script lang="ts" setup>
import addProduct from "./addProduct.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { productList, productCopy, productDelete } from "@/service/dp.ts";
import { companyCheck } from "@/service/dp.ts";

const router = useRouter();
const listData: any = ref([]);
const addProductRef: any = ref(null);
const addProductFlag: any = ref(false);
let loading = false;
let params = {
  current: 1,
  size: 20,
}
const scrollbarRef = ref<any>(null);
let totalNum = 0;
let container: any = null;
// 点击添加
function handleAdd() {
  if (!addProductFlag.value) {
    ElMessage.error({ message: "暂无权限!" });
    return;
  }
  addProductRef.value.showDrawer();
}

// 点击list查看详情
function handleAddDetail(id: string) {
  router.push({ name: 'details', query: { id } });
}

/**
 * 监听宽度，计算显示卡片个数
 */
const column = ref(4);
const windowChange = () => {
  if (window.innerWidth <= 1440) {
    column.value = 3;
  } else if (window.innerWidth > 1440 && window.innerWidth <= 1600) {
    column.value = 3;
  } else if (window.innerWidth > 1600) {
    column.value = 4;
  }
};

function addSuccess() {
  params.current = 1;
  getProductList();
}

async function getProductList() {
  let res: any = await productList(params);
  if (res.code == 200) {
    listData.value = params.current > 1 ? [...listData.value, ...res.data.records] : res.data.records;
    loading = false;
    totalNum = res.data.total;
    if(params.current === 1 && container.scrollTop > 0) {
      scrollToTop();
    }
    params.current += 1;
  } else {
    ElMessage.error(res.msg);
    loading = false;
  }
}

function scrollToTop() {
  if (scrollbarRef.value) {
    scrollbarRef.value.setScrollTop(0); // 将滚动条设置到顶部
  }
}

function handleScroll() {
  const scrollTop = container.scrollTop;
  const scrollHeight = container.scrollHeight;
  const clientHeight = container.clientHeight;
  if (listData.value.length === totalNum) { return; }
  if (scrollTop + clientHeight >= scrollHeight - 160) {
    if (!loading) {
      loading = true;
      getProductList();
    }
  }
}
async function getCompanyStatus() {
  let res: any = await companyCheck();
  if (res.code == 200) {
    addProductFlag.value = true;
    getProductList();
  } else {
    ElMessage.error(res.msg);
  }
}

async function handleCopy(val: any) {
  try {
    await ElMessageBox.confirm(`复制名称为: ${val.name} 的产品？`, "操作提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    });
    const res: any = await productCopy({ id: val.id });
    if (res.code == 200) {
      ElMessage.success({ message: "复制产品成功!" });
      params.current = 1;
      getProductList();
    } else {
      ElMessage.error({ message: "复制产品失败!" });
    }
  } catch (error) { }
}

async function handleDel(val: any) {
  if (val.status === '2') {
    await ElMessageBox.confirm('产品审核通过后不能删除', "操作提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    });
    return;
  } else {
    try {
      await ElMessageBox.confirm(`删除名称为: ${val.name} 的产品？`, "操作提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      });
      const res: any = await productDelete({ id: val.id });
      if (res.code == 200) {
        params.current = 1;
        ElMessage.success("删除成功");
        getProductList();
      } else {
        ElMessage.error({ message: "删除操作失败!" });
      }
    } catch (error) { }
  }
}

onMounted(() => {
  if (scrollbarRef.value) {
    container = scrollbarRef.value.$el.querySelector('.el-scrollbar__wrap');
    container.addEventListener('scroll', handleScroll);
  }
  getCompanyStatus();
  windowChange(); // 初始化
  window.onresize = () => {
    windowChange();
  };
});
</script>
<style>
.custom-popover-aig {
  padding: 0 !important;
  min-width: 109px !important;
  width: 109px !important;
}
</style>
<style scoped lang="scss">
.popover-btn {
  padding: 8px;
}

.popover-item {
  display: flex;
  align-items: center;
  height: 32px;
  font-family: Source Han Sans CN, Source Han Sans CN;
  font-weight: 400;
  font-size: 14px;
  color: #000000;
  font-style: normal;
  text-transform: none;

  img {
    margin-left: 8px;
  }

  span {
    display: inline-block;
    margin-left: 16px;
    cursor: pointer;
  }

  &:nth-child(1) {
    margin-bottom: 4px;
  }
}

.product-content {
  width: 100%;

  .list-card {
    display: grid;
    grid-gap: 16px;
    grid-template-columns: repeat(v-bind(column), 1fr);
    margin-right: 16px;

    .add-card {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      cursor: pointer;

      span {
        display: inline-block;
        margin-top: 8px;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 400;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.6);
        font-style: normal;
        text-transform: none;
      }
    }

    .list-card-item {
      position: relative;
      background:#ffffff ;
      border-radius: 0px 0px 0px 0px;
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
      cursor: pointer;
      max-width: 401px;
      height: 180px;

      .product_normal {
        margin: 16px 24px;

        .normal-one,
        .normal-two {
          display: flex;
        }

        .normal-one {
          justify-content: space-between;
          height: 24px;
          align-items: center;
          margin-bottom: 8px;

          .one-left {
            font-family: Source Han Sans CN, Source Han Sans CN;
            font-weight: 400;
            font-size: 16px;
            color: rgba(0, 0, 0, 0.9);
            line-height: 19px;
            font-style: normal;
            text-transform: none;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp:2;
            overflow: hidden;
          }
        }

        .normal-two {
          height: 18px;
          align-items: center;
          margin-bottom: 8px;
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.6);
          text-align: left;
          font-style: normal;
          text-transform: none;

          .two-left {
            width: 100px;
            margin-right: 10px;
          }

          .two-right {
            flex: 1;
          }
        }
      }
    }
  }
}
</style>
